<?php

namespace App\Admin\Forms;

use App\Models\User;
use App\Models\UserBalance;
use App\Models\UserBalanceFlow;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Topup extends Form implements LazyRenderable
{

    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // return $this->response()->error('Your error message.');
        $userId = $this->payload['user_id'] ?? null;

        if (!$userId) {
            return $this->response()->error('user_id 参数错误，请联系开发人员');
        }

        $user = User::find($userId);

        if (empty($user)) {
            return $this->response()->error('用户不存在，请联系开发人员');
        }

        $balance = $input['balance'] ?? null;
        if (empty($balance)) {
            return $this->response()->error('请输入金额');
        }

        $userBalance = UserBalance::where('user_id', $userId)
            ->get()->first();

        if (empty($userBalance)) {
            $userBalance = new UserBalance();
        }

        DB::beginTransaction();
        try {

            // 更新用户余额表
            $userBalance->user_id = $userId;
            $userBalance->balance += $balance;
            $userBalance->save();

            // 插入流水
            $userBalanceFlow = new UserBalanceFlow();
            $userBalanceFlow->title = '充值';
            $userBalanceFlow->user_id = $userId;
            $userBalanceFlow->balance = $input['balance'];
            $userBalanceFlow->balance_rest += $input['balance'];
            $userBalanceFlow->type = 0;
            $userBalanceFlow->from = $input['type'];
            $userBalanceFlow->operator = '后台管理员';
            $userBalanceFlow->comment = $input['comment'];
            $userBalanceFlow->created_at = $input['created_at'];
            $userBalanceFlow->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->response()->error($e->getMessage());
        }


        return $this
				->response()
				->success('保存成功')
				->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->date('created_at', '充值日期')->default(Carbon::now()->format('Y-m-d'));
        $this->decimal('balance', '金额')->required();
        $this->select('type')->options([0 => '现金', 1 => '微信'])->default(0);
        $this->textarea('comment', '备注');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [];
    }

}
